package com.cskaoyan.realm;

//import com.cskaoyan.mapper.UserMapper;

import com.cskaoyan.Utils.MyUtils;
import com.cskaoyan.mapper.systemmapper.AdminMapper;
import com.cskaoyan.mapper.systemmapper.PermissionMapper;
import com.cskaoyan.mapper.systemmapper.RoleMapper;
import com.cskaoyan.mapper.usermapper.UserMapper;
import com.cskaoyan.service.authservice.AuthService;
import com.cskaoyan.service.authservice.AuthServiceImpl;
import com.cskaoyan.service.wx.WxAuthService;
import com.cskaoyan.service.wx.WxAuthServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.util.List;

@Component
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    AuthServiceImpl authServiceImpl;
    @Autowired
    WxAuthService wxAuthService;
    @Autowired
    UserMapper userMapper;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String userOrAdmin = (String) MyUtils.getSession().getAttribute("UserOrAdmin");
        String credential = null;
        if (userOrAdmin != null) {
            if (userOrAdmin.equals("admin"))
                credential = adminMapper.selectPasswordByUsername(username);
            else if (userOrAdmin.equals("user"))
                credential = userMapper.selectPasswordByUsername(username);
        }


        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, credential, this.getName());
        return authenticationInfo;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //用户登陆认证后，不需要授权
        if (MyUtils.getSession().getAttribute("UserOrAdmin").equals("User"))
            return new SimpleAuthorizationInfo();
        String username = (String) principalCollection.getPrimaryPrincipal();

        List<String> permissions = authServiceImpl.selectPermissonsByUsername(username);


        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        authorizationInfo.addStringPermissions(permissions);
//        authorizationInfo.addStringPermissions(Arrays.asList("perm1"));


        return authorizationInfo;
    }


}
